<template>
  <view class="container">
    <!-- 聊天消息区域 -->
    <view class="chat-area">
      <scroll-view
        class="message-list"
        scroll-y
        :scroll-top="scrollTop"
        scroll-with-animation
      >
        <view
          v-for="(message, index) in messages"
          :key="index"
          class="message-item"
          :class="{ 'message-right': message.type === 'user' }"
        >
          <view class="avatar">
            <image
              :src="message.type === 'user' ? '/static/user-avatar.jpg' : '/static/doctor-avatar.jpg'"
              class="avatar-img"
            />
          </view>
          <view class="message-content">
            <view class="message-bubble" :class="{ 'bubble-user': message.type === 'user' }">
              {{ message.content }}
            </view>
            <view class="message-time">{{ message.time }}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <van-field
        v-model="inputMessage"
        placeholder="请输入您要咨询的问题..."
        type="textarea"
        :autosize="{ minHeight: 60, maxHeight: 120 }"
        @confirm="sendMessage"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendMessage">
            发送
          </van-button>
        </template>
      </van-field>
    </view>

    <!-- 医生状态栏 -->
    <view class="doctor-status">
      <van-notice-bar
        :text="doctorStatusText"
        left-icon="volume-o"
        :scrollable="false"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";

interface Message {
  type: 'user' | 'doctor';
  content: string;
  time: string;
}

const inputMessage = ref("");
const scrollTop = ref(0);
const doctorStatusText = ref("医生正在线，请耐心等待回复...");

const messages = ref<Message[]>([
  {
    type: "doctor",
    content: "您好，我是您的主治医生，请详细描述您的症状。",
    time: "14:30"
  }
]);

const formatTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    return;
  }

  const newMessage: Message = {
    type: "user",
    content: inputMessage.value.trim(),
    time: formatTime()
  };

  messages.value.push(newMessage);
  inputMessage.value = "";

  scrollToBottom();

  setTimeout(() => {
    simulateDoctorReply();
  }, 2000 + Math.random() * 3000);
};

const simulateDoctorReply = () => {
  const replies = [
    "根据您的描述，建议您注意休息，多喝水。",
    "请问这种症状持续多长时间了？",
    "建议您到医院进行进一步检查。",
    "这种情况比较常见，不用过于担心。",
    "请按时服药，注意饮食清淡。"
  ];

  const randomReply = replies[Math.floor(Math.random() * replies.length)];

  messages.value.push({
    type: "doctor",
    content: randomReply,
    time: formatTime()
  });

  scrollToBottom();
};

const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query.select('.message-list').scrollOffset((res: any) => {
      scrollTop.value = res.scrollHeight;
    }).exec();
  });
};

onLoad(() => {
  console.log("线上问诊聊天页面 onLoad");
  scrollToBottom();
});

onUnload(() => {
  console.log("线上问诊聊天页面 onUnload");
});
</script>

<style lang="scss">
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.doctor-status {
  flex-shrink: 0;
}

.chat-area {
  flex: 1;
  overflow: hidden;
  
  .message-list {
    height: 100%;
    padding: 24rpx;
  }
}

.message-item {
  display: flex;
  margin-bottom: 32rpx;
  
  &.message-right {
    flex-direction: row-reverse;
    
    .message-content {
      align-items: flex-end;
    }
  }
}

.avatar {
  flex-shrink: 0;
  margin: 0 16rpx;
  
  .avatar-img {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
  }
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 60%;
}

.message-bubble {
  padding: 24rpx 32rpx;
  border-radius: 32rpx;
  background: white;
  word-wrap: break-word;
  
  &.bubble-user {
    background: #07C160;
    color: white;
  }
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
  text-align: center;
}

.input-area {
  flex-shrink: 0;
  background: white;
  padding: 16rpx;
  border-top: 1rpx solid #eee;
}
</style>